package com.simple.proxy.mybatis.proxy;

import com.simple.proxy.mybatis.annotations.Transaction;
import com.simple.proxy.mybatis.db.DbTools;
import com.simple.proxy.mybatis.db.TransactionManager;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;

public class TransactionProxy implements MethodInterceptor {
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
//        System.out.println("========Cglib动态代理开始=======");
        Object result = null;
        //判断方法是否加了Transaction，如果没有加则不开启事务
        if(!method.isAnnotationPresent(Transaction.class)){
            result = methodProxy.invokeSuper(o, objects);
        } else {
            //反之，如果方法加了Transaction，则开启事务
            Connection connection = TransactionManager.getConnection();
            System.out.println(connection.getClass());
            if(connection != null){
                try {
                    connection.setAutoCommit(false);
                    result = methodProxy.invokeSuper(o, objects);
                    //提交事务
                    connection.commit();
                    return result;
                } catch (SQLException e) {
                    e.printStackTrace();
                    if(connection != null){
                        //发生异常则回滚事务
                        try {
                            connection.rollback();
                        } catch (SQLException e1) {
                            e1.printStackTrace();
                        }
                    }
                } finally {
                    if(connection != null){
                        DbTools.release(connection,null,null);
                    }
                }
            }
        }
//        System.out.println("========Cglib动态代理结束=======");
        return result;
    }
}
